const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 8080;

const server = http.createServer((req, res) => {
    // 设置CORS头部
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

    // 修正路径逻辑，支持从js、css、public目录提供文件
    let filePath;
    
    if (req.url === '/') {
        filePath = path.join(__dirname, 'public', 'index.html');
    } else if (req.url.startsWith('/js/')) {
        filePath = path.join(__dirname, req.url);
    } else if (req.url.startsWith('/css/')) {
        filePath = path.join(__dirname, req.url);
    } else if (req.url.startsWith('/admin/')) {
        filePath = path.join(__dirname, req.url);
    } else {
        filePath = path.join(__dirname, 'public', req.url);
    }

    const extname = path.extname(filePath).toLowerCase();
    const mimeTypes = {
        '.html': 'text/html; charset=utf-8',
        '.js': 'text/javascript; charset=utf-8', 
        '.css': 'text/css; charset=utf-8',
        '.json': 'application/json',
        '.png': 'image/png',
        '.jpg': 'image/jpg',
        '.gif': 'image/gif',
        '.svg': 'image/svg+xml',
        '.wav': 'audio/wav',
        '.mp4': 'video/mp4',
        '.woff': 'application/font-woff',
        '.ttf': 'application/font-ttf',
        '.eot': 'application/vnd.ms-fontobject',
        '.otf': 'application/font-otf',
        '.wasm': 'application/wasm'
    };

    const contentType = mimeTypes[extname] || 'application/octet-stream';

    fs.readFile(filePath, (error, content) => {
        if (error) {
            if (error.code === 'ENOENT') {
                console.log(`❌ 文件未找到: ${filePath}`);
                // 404 - 文件未找到
                res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
                res.end('404 - 文件未找到');
            } else {
                console.log(`❌ 服务器错误: ${error.code} - ${filePath}`);
                res.writeHead(500);
                res.end('Server Error: ' + error.code);
            }
        } else {
            console.log(`✅ 文件请求成功: ${req.url}`);
            res.writeHead(200, { 'Content-Type': contentType });
            res.end(content, 'utf-8');
        }
    });
});

server.listen(PORT, () => {
    console.log('🌐 前端服务器启动成功!');
    console.log(`📡 服务器地址: http://localhost:${PORT}`);
    console.log(`📄 主页: http://localhost:${PORT}/index.html`);
    console.log(`📝 提交页面: http://localhost:${PORT}/submit.html`);
    console.log('⏰ 启动时间:', new Date().toLocaleString());
    console.log('='.repeat(50));
});

// 优雅关闭
process.on('SIGTERM', () => {
    console.log('🛑 前端服务器关闭');
    server.close(() => {
        process.exit(0);
    });
});

process.on('SIGINT', () => {
    console.log('🛑 前端服务器关闭');
    server.close(() => {
        process.exit(0);
    });
}); 